<!--
豆包交互页面 - 与豆包AI进行营销方案生成的交互
功能：接收用户需求，调用豆包API生成营销方案
-->
<template>
  <div class="doubao-page">
    <div class="container">
      <!-- 页面头部 -->
      <div class="page-header">
        <div class="header-content">
          <button @click="goBack" class="back-btn">
            <ArrowLeft :size="16" />
            返回表单
          </button>
          <div class="header-info">
            <h1>豆包AI营销方案生成</h1>
            <p>基于您的需求，让豆包为您生成专业的营销方案</p>
          </div>
        </div>
      </div>

      <!-- 主要内容区域 -->
      <div class="main-content">
        <div class="content-layout">
          <!-- 左侧需求信息面板 -->
          <div class="sidebar">
            <div class="requirement-panel">
              <h3>需求信息</h3>
              <div class="requirement-content">
                <div class="requirement-item">
                  <label>核心目标</label>
                  <div class="requirement-value">{{ requirementData?.core_goal || '未填写' }}</div>
                </div>
                <div class="requirement-item">
                  <label>目标受众</label>
                  <div class="requirement-value">{{ requirementData?.target_audience || '未填写' }}</div>
                </div>
                <div class="requirement-item">
                  <label>人均预算</label>
                  <div class="requirement-value">{{ requirementData?.budget_per_person || '未填写' }}</div>
                </div>
                <div class="requirement-item">
                  <label>方案侧重点</label>
                  <div class="requirement-value">{{ requirementData?.focus_point || '未填写' }}</div>
                </div>
                <div class="requirement-item">
                  <label>礼品类型偏好</label>
                  <div class="requirement-value">{{ requirementData?.gift_preference || '未填写' }}</div>
                </div>
                <div class="requirement-item">
                  <label>具体产品</label>
                  <div class="requirement-value">{{ requirementData?.specific_product || '未填写' }}</div>
                </div>
                <div class="requirement-item">
                  <label>客户偏好</label>
                  <div class="requirement-value">{{ requirementData?.customer_preference || '未填写' }}</div>
                </div>
                <div class="requirement-item">
                  <label>客户痛点</label>
                  <div class="requirement-value">{{ requirementData?.customer_pain_points || '未填写' }}</div>
                </div>
              </div>
              
              <!-- 操作按钮 -->
              <div class="action-buttons">
                <button @click="sendToDoubao" class="send-btn" :disabled="!isIframeLoaded">
                  <Send :size="16" />
                  发送需求给豆包
                </button>
                <button @click="refreshIframe" class="refresh-btn">
                  <RefreshCw :size="16" />
                  刷新豆包
                </button>
                <button @click="saveSolution" class="save-btn" :disabled="!generatedSolution">
                  <Save :size="16" />
                  保存方案
                </button>
                <button @click="confirmPlan" class="confirm-btn" :disabled="!savedSolution">
                  <Check :size="16" />
                  确认方案并继续
                </button>
              </div>
            </div>
            
            <!-- 方案预览面板 -->
            <div v-if="generatedSolution" class="solution-panel">
              <h3>生成的方案</h3>
              <div class="solution-content">
                <div class="solution-text">{{ generatedSolution }}</div>
                <div class="solution-actions">
                  <button @click="editSolution" class="edit-btn">
                    <Edit :size="16" />
                    编辑方案
                  </button>
                  <button @click="regenerateSolution" class="regenerate-btn">
                    <RotateCcw :size="16" />
                    重新生成
                  </button>
                </div>
              </div>
            </div>
          </div>

          <!-- 右侧豆包交互面板 -->
          <div class="main-panel">
            <div class="iframe-container">
              <div class="iframe-header">
                <h3>豆包AI助手</h3>
                <div class="iframe-controls">
                  <div class="connection-status" :class="{ 'connected': isIframeLoaded }">
                    <div class="status-dot"></div>
                    <span>{{ isIframeLoaded ? '已连接' : '连接中...' }}</span>
                  </div>
                  <button @click="toggleFullscreen" class="fullscreen-btn">
                    <Maximize2 :size="16" />
                  </button>
                </div>
              </div>
              <iframe 
                ref="doubaoIframe"
                :src="doubaoUrl"
                class="doubao-iframe"
                @load="onIframeLoad"
                frameborder="0"
                allowfullscreen
                sandbox="allow-same-origin allow-scripts allow-forms allow-popups allow-top-navigation"
              ></iframe>
              <div v-if="isLoading" class="loading-overlay">
                <div class="loading-spinner"></div>
                <p>正在加载豆包AI...</p>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed, nextTick, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { useMarketingStore } from '../stores/marketing'
import { ArrowLeft, Send, RefreshCw, Check, Maximize2, Save, Edit, RotateCcw } from 'lucide-vue-next'
import api from '../utils/api'
import { copyText, getClipboardCapabilities } from '../utils/clipboard'

const router = useRouter()
const marketingStore = useMarketingStore()

// 响应式数据
const requirementData = computed(() => marketingStore.getRequirementData())
const doubaoIframe = ref(null)
const isLoading = ref(true)
const isIframeLoaded = ref(false)
const generatedSolution = ref('')
const savedSolution = ref('')
const isFullscreen = ref(false)
const doubaoUrl = ref('https://www.doubao.com/chat/')

// 生命周期
onMounted(() => {
  // 如果没有需求数据，跳转回首页
  if (!requirementData.value) {
    router.push('/')
    return
  }
  
  // 监听全屏状态变化
  document.addEventListener('fullscreenchange', handleFullscreenChange)
  
  // 初始化iframe
  initializeIframe()
})

// 方法
const goBack = () => {
  router.push('/')
}

const initializeIframe = () => {
  isLoading.value = true
  // iframe加载完成后的处理
  nextTick(() => {
    if (doubaoIframe.value) {
      doubaoIframe.value.onload = onIframeLoad
    }
  })
}

const onIframeLoad = () => {
  isLoading.value = false
  isIframeLoaded.value = true
  console.log('豆包iframe加载完成')
  
  // 尝试与iframe建立通信
  setupIframeMessaging()
}

const setupIframeMessaging = () => {
  // 监听来自iframe的消息
  window.addEventListener('message', (event) => {
    // 验证消息来源
    if (event.origin !== 'https://www.doubao.com') {
      return
    }
    
    // 处理不同类型的消息
    if (event.data.type === 'solution_generated') {
      generatedSolution.value = event.data.content
    } else if (event.data.type === 'iframe_ready') {
      // iframe准备就绪，可以发送数据
      console.log('豆包iframe准备就绪')
    }
  })
}

const sendToDoubao = async () => {
  try {
    // 调用后端API生成完整的提示词
    const result = await api.post('/prompts/generate', requirementData.value)
    
    if (!result.success) {
      throw new Error(result.message || '生成提示词失败')
    }
    
    // 使用生成的完整提示词
    const fullPrompt = result.data.prompt
    
    // 尝试通过postMessage发送数据到iframe
    if (doubaoIframe.value && doubaoIframe.value.contentWindow) {
      doubaoIframe.value.contentWindow.postMessage({
        type: 'send_requirement',
        data: fullPrompt
      }, 'https://www.doubao.com')
    }
    
    // 使用新的智能复制功能
    const copyResult = await copyText(fullPrompt, {
      showFallbackDialog: true,
      fallbackTitle: '豆包AI提示词'
    })
    
    if (copyResult.success) {
      alert(`✅ 完整提示词已发送给豆包AI，同时${copyResult.message}！\n\n💡 如果自动发送失败，请在豆包界面中粘贴使用 (Ctrl+V)\n\n📋 提示词预览：\n${fullPrompt.substring(0, 200)}...`)
    } else {
      // 如果复制失败，手动复制对话框已经显示，只需要简单提示
      console.log('复制方法:', copyResult.method, '消息:', copyResult.message)
    }
    
  } catch (error) {
    console.error('发送需求失败:', error)
    // 降级到旧版本的简单需求文本
    const requirementText = buildRequirementText()
    
    const copyResult = await copyText(requirementText, {
      showFallbackDialog: true,
      fallbackTitle: '营销需求信息（简化版）'
    })
    
    if (copyResult.success) {
      alert(`⚠️ API调用失败，已使用简化版需求信息并${copyResult.message}。\n\n❌ 错误信息：${error.message}\n\n💡 请在豆包界面中粘贴使用`)
    } else {
      console.log('降级复制失败:', copyResult.message)
    }
  }
}

const buildRequirementText = () => {
  const data = requirementData.value
  if (!data) return '暂无需求数据'
  
  return `请帮我制定一个营销方案，具体需求如下：

🎯 核心目标：${data.core_goal || '未填写'}
👥 目标受众：${data.target_audience || '未填写'}
💰 人均预算：${data.budget_per_person || '未填写'}
🎪 方案侧重点：${data.focus_point || '未填写'}
🎁 礼品类型偏好：${data.gift_preference || '未填写'}
📦 具体产品：${data.specific_product || '未填写'}
❤️ 客户偏好：${data.customer_preference || '未填写'}
😰 客户痛点：${data.customer_pain_points || '未填写'}

请基于以上信息，为我制定一个详细的营销方案，包括具体的执行步骤、预期效果和注意事项。`
}

const saveSolution = () => {
  if (!generatedSolution.value) {
    // 如果没有自动获取到方案，让用户手动输入
    const userSolution = prompt('请粘贴豆包生成的营销方案：')
    if (userSolution && userSolution.trim()) {
      generatedSolution.value = userSolution.trim()
    } else {
      alert('请先获取豆包生成的方案')
      return
    }
  }
  
  savedSolution.value = generatedSolution.value
  marketingStore.setGeneratedPlan({
    content: savedSolution.value,
    source: 'doubao',
    timestamp: new Date().toISOString()
  })
  
  alert('方案已保存！')
}

const editSolution = () => {
  const editedSolution = prompt('编辑营销方案：', generatedSolution.value)
  if (editedSolution !== null) {
    generatedSolution.value = editedSolution
  }
}

const regenerateSolution = () => {
  if (confirm('确定要重新生成方案吗？这将清除当前方案。')) {
    generatedSolution.value = ''
    savedSolution.value = ''
    sendToDoubao()
  }
}

const confirmPlan = () => {
  if (!savedSolution.value) {
    alert('请先保存方案')
    return
  }
  
  if (confirm('确认当前方案并继续生成PPT？')) {
    router.push('/kimi')
  }
}

const refreshIframe = () => {
  isLoading.value = true
  isIframeLoaded.value = false
  if (doubaoIframe.value) {
    doubaoIframe.value.src = doubaoUrl.value
  }
}

const toggleFullscreen = () => {
  const iframeContainer = doubaoIframe.value?.parentElement
  if (!iframeContainer) return
  
  if (!isFullscreen.value) {
    if (iframeContainer.requestFullscreen) {
      iframeContainer.requestFullscreen()
      isFullscreen.value = true
    }
  } else {
    if (document.exitFullscreen) {
      document.exitFullscreen()
      isFullscreen.value = false
    }
  }
}

// 监听全屏状态变化
const handleFullscreenChange = () => {
  isFullscreen.value = !!document.fullscreenElement
}

// 清理事件监听器
const cleanup = () => {
  document.removeEventListener('fullscreenchange', handleFullscreenChange)
  window.removeEventListener('message', setupIframeMessaging)
}

// 组件卸载时清理
onUnmounted(cleanup)
</script>

<style scoped>
.doubao-page {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  width: 100%;
  overflow-x: hidden;
}

.container {
  width: 100%;
  margin: 0;
  padding: 0 1rem;
  max-width: none;
}

.page-header {
  background: rgba(255, 255, 255, 0.1);
  backdrop-filter: blur(10px);
  border-bottom: 1px solid rgba(255, 255, 255, 0.2);
  padding: 0.75rem 0;
  margin-bottom: 1rem;
}

.header-content {
  display: flex;
  align-items: center;
  gap: 1rem;
}

.back-btn {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  padding: 0.5rem 1rem;
  background: rgba(255, 255, 255, 0.2);
  border: 1px solid rgba(255, 255, 255, 0.3);
  border-radius: 8px;
  color: white;
  text-decoration: none;
  transition: all 0.3s ease;
  cursor: pointer;
}

.back-btn:hover {
  background: rgba(255, 255, 255, 0.3);
  transform: translateY(-2px);
}

.header-info h1 {
  color: white;
  margin: 0;
  font-size: 1.5rem;
  font-weight: 600;
}

.header-info p {
  color: rgba(255, 255, 255, 0.8);
  margin: 0.25rem 0 0 0;
  font-size: 0.9rem;
}

.main-content {
  padding-bottom: 2rem;
}

.content-layout {
  display: grid;
  grid-template-columns: 300px 1fr;
  gap: 1rem;
  height: calc(100vh - 120px);
  min-height: 600px;
  width: 100%;
}

.sidebar {
  display: flex;
  flex-direction: column;
  gap: 0.75rem;
  overflow-y: auto;
}

.requirement-panel,
.solution-panel {
  background: rgba(255, 255, 255, 0.95);
  border-radius: 12px;
  padding: 1rem;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.2);
}

.requirement-panel h3,
.solution-panel h3 {
  margin: 0 0 1rem 0;
  color: #333;
  font-size: 1.1rem;
  font-weight: 600;
}

.requirement-content {
  display: flex;
  flex-direction: column;
  gap: 0.75rem;
  margin-bottom: 1.5rem;
}

.requirement-item {
  display: flex;
  flex-direction: column;
  gap: 0.25rem;
}

.requirement-item label {
  font-size: 0.85rem;
  font-weight: 500;
  color: #666;
}

.requirement-value {
  font-size: 0.9rem;
  color: #333;
  padding: 0.5rem;
  background: #f8f9fa;
  border-radius: 6px;
  border: 1px solid #e9ecef;
  word-wrap: break-word;
}

.action-buttons {
  display: flex;
  flex-direction: column;
  gap: 0.75rem;
}

.send-btn,
.refresh-btn,
.save-btn,
.confirm-btn,
.edit-btn,
.regenerate-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 0.5rem;
  padding: 0.75rem 1rem;
  border: none;
  border-radius: 8px;
  font-size: 0.9rem;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
  text-decoration: none;
}

.send-btn {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
}

.send-btn:hover:not(:disabled) {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
}

.refresh-btn {
  background: linear-gradient(135deg, #ffecd2 0%, #fcb69f 100%);
  color: #8b4513;
}

.refresh-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(252, 182, 159, 0.4);
}

.save-btn {
  background: linear-gradient(135deg, #a8edea 0%, #fed6e3 100%);
  color: #2c3e50;
}

.save-btn:hover:not(:disabled) {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(168, 237, 234, 0.4);
}

.confirm-btn {
  background: linear-gradient(135deg, #56ab2f 0%, #a8e6cf 100%);
  color: white;
}

.confirm-btn:hover:not(:disabled) {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(86, 171, 47, 0.4);
}

.send-btn:disabled,
.save-btn:disabled,
.confirm-btn:disabled {
  background: #ccc;
  cursor: not-allowed;
  transform: none;
  box-shadow: none;
  opacity: 0.6;
}

.solution-panel {
  margin-top: 1rem;
}

.solution-content {
  display: flex;
  flex-direction: column;
  gap: 1rem;
}

.solution-text {
  background: #f8f9fa;
  border: 1px solid #e9ecef;
  border-radius: 8px;
  padding: 1rem;
  font-size: 0.9rem;
  line-height: 1.5;
  color: #333;
  max-height: 200px;
  overflow-y: auto;
  white-space: pre-wrap;
}

.solution-actions {
  display: flex;
  gap: 0.5rem;
}

.edit-btn {
  flex: 1;
  background: linear-gradient(135deg, #74b9ff 0%, #0984e3 100%);
  color: white;
  font-size: 0.8rem;
  padding: 0.5rem;
}

.regenerate-btn {
  flex: 1;
  background: linear-gradient(135deg, #fd79a8 0%, #e84393 100%);
  color: white;
  font-size: 0.8rem;
  padding: 0.5rem;
}

.edit-btn:hover,
.regenerate-btn:hover {
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
}

.main-panel {
  display: flex;
  flex-direction: column;
}

.iframe-container {
  background: rgba(255, 255, 255, 0.95);
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  backdrop-filter: blur(10px);
  border: 1px solid rgba(255, 255, 255, 0.2);
  height: 100%;
  display: flex;
  flex-direction: column;
  position: relative;
}

.iframe-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 1rem 1.5rem;
  background: rgba(255, 255, 255, 0.8);
  border-bottom: 1px solid rgba(0, 0, 0, 0.1);
}

.iframe-header h3 {
  margin: 0;
  color: #333;
  font-size: 1.1rem;
  font-weight: 600;
}

.iframe-controls {
  display: flex;
  align-items: center;
  gap: 1rem;
}

.connection-status {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  font-size: 0.85rem;
  color: #666;
}

.status-dot {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background: #dc3545;
  animation: pulse 2s infinite;
}

.connection-status.connected .status-dot {
  background: #28a745;
  animation: none;
}

.connection-status.connected {
  color: #28a745;
}

@keyframes pulse {
  0% {
    opacity: 1;
  }
  50% {
    opacity: 0.5;
  }
  100% {
    opacity: 1;
  }
}

.fullscreen-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 32px;
  height: 32px;
  border: none;
  border-radius: 6px;
  background: rgba(0, 0, 0, 0.1);
  color: #666;
  cursor: pointer;
  transition: all 0.3s ease;
}

.fullscreen-btn:hover {
  background: rgba(0, 0, 0, 0.2);
  color: #333;
}

.doubao-iframe {
  width: 100%;
  height: 100%;
  border: none;
  background: white;
  flex: 1;
}

.loading-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(255, 255, 255, 0.9);
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 1rem;
  z-index: 10;
}

.loading-spinner {
  width: 40px;
  height: 40px;
  border: 3px solid #f3f3f3;
  border-top: 3px solid #667eea;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.loading-overlay p {
  color: #666;
  font-size: 0.9rem;
  margin: 0;
}

/* 响应式设计 */
@media (max-width: 1400px) {
  .content-layout {
    grid-template-columns: 280px 1fr;
    gap: 1rem;
  }
}

@media (max-width: 1200px) {
  .content-layout {
    grid-template-columns: 260px 1fr;
    gap: 0.75rem;
  }
  
  .container {
    padding: 0 0.75rem;
  }
}

@media (max-width: 1024px) {
  .content-layout {
    grid-template-columns: 240px 1fr;
    gap: 0.75rem;
  }
  
  .requirement-panel,
  .solution-panel {
    padding: 0.75rem;
  }
}

@media (max-width: 768px) {
  .content-layout {
    grid-template-columns: 1fr;
    gap: 0.75rem;
    height: auto;
  }
  
  .sidebar {
    order: 2;
  }
  
  .main-panel {
    order: 1;
    height: 65vh;
    min-height: 450px;
  }
  
  .requirement-panel,
  .solution-panel {
    padding: 0.75rem;
  }
  
  .header-content {
    flex-direction: column;
    align-items: flex-start;
    gap: 0.5rem;
  }
  
  .container {
    padding: 0 0.5rem;
  }
}

@media (max-width: 480px) {
  .main-content {
    padding-bottom: 1rem;
  }
  
  .requirement-panel,
  .solution-panel {
    padding: 0.75rem;
  }
  
  .iframe-header {
    padding: 0.75rem 1rem;
  }
  
  .send-btn,
  .refresh-btn,
  .save-btn,
  .confirm-btn {
    padding: 0.625rem 0.75rem;
    font-size: 0.85rem;
  }
  
  .solution-actions {
    flex-direction: column;
  }
  
  .edit-btn,
  .regenerate-btn {
    width: 100%;
    margin-bottom: 0.5rem;
  }
  
  .container {
    padding: 0 0.5rem;
  }
  
  .main-panel {
    height: 60vh;
    min-height: 400px;
  }
}
</style>